import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author 35326
 * 2021/4/3 12:49
 * Blob类型字段的测试
 */
public class BlobTest {
	public static final Properties properties = new Properties();
	public static String user;
	public static String password;
	public static String url;
	public static String driverName;
	static{
		try {
			properties.load(new FileInputStream("mysql.properties"));
			driverName = properties.getProperty("driverName");
			user=properties.getProperty("user");
			password=properties.getProperty("password");
			url=properties.getProperty("url");
			//加载数据库驱动
			Class.forName(driverName);
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}


	}
	public static void main(String[] args) {
		boolean execute=false;
		try(Connection connection = DriverManager.getConnection(url, user, password);
			PreparedStatement preparedStatement = connection.prepareStatement("select * from blobtest");
			FileOutputStream fileOutputStream = new FileOutputStream("IMG2.jpg");) {
//			"insert into blobtest values(?)"

//			preparedStatement.setBlob(1,new FileInputStream("IMG.jpg"));
			ResultSet resultSet = preparedStatement.executeQuery();
			while(resultSet.next())
			{
				Blob blob = resultSet.getBlob(1);
				InputStream binaryStream = blob.getBinaryStream();
				byte[] bytes = new byte[1024];
				int len=-1;
				while((len=binaryStream.read(bytes))!=-1){
					fileOutputStream.write(bytes,0,len);
				}
			}
		} catch (Exception throwables) {
			throwables.printStackTrace();
		} finally {
			System.out.println();
		}
	}
}
